#!/usr/bin/env python
#coding=UTF-8
'''
Created on 2010-10-26

@author: zarra
'''

import cv
from fft import ZFft
from common import Question,pow_ne1,amplitude_plot,matrix2image, image2matrix
from numpy import sqrt,mat,arctan,pi
#from numpy.fft import fft2
image_file='../data'

fft2 = ZFft.fft2d
ifft2=ZFft.ifft2d

def image2matrix2(image):
        height,width = image.height,image.width
        m=list()
        for i in range(height):
            row = [image[i,j]  for j in range(width)]
            m.append(row)   
        return mat(m)
    
class Q4(Question):
    def __init__(self,image,m='show'):
        super(self.__class__,self).__init__('Q4',image,m)
                
    def action(self):
        image = self.image
        m=list()
    
        for i in range(image.height):
            row = [pow_ne1(image[i,j],i,j)  for j in range(image.width)]
            m.append(row)
        m=mat(m,complex)
        fft_result = fft2(m)
        fft_result_b=fft2(image2matrix2(image))
        
        
        #计算相位谱
        phanse =  cv.CreateImage((image.width,image.height), image.depth, image.channels)
        u=256/pi
        for i in range(phanse.width):
            for j in range(phanse.height):
                real=fft_result[j,i].real
                imag=fft_result[j,i].imag
                p=(arctan(imag/real)+pi/2)*u
                phanse[j,i]=p
                
        #反变换
        ifft_result = ifft2(fft_result)
        ifft_image = matrix2image(ifft_result)
        #频谱
        fft_amp = amplitude_plot(fft_result)
        
        
        self.display(phanse, 'fft_phanse')
        self.display(fft_amp, 'fft_amp')
        self.display(amplitude_plot(fft_result_b), 'fft_amp_4c')
        self.display(ifft_image, 'ifft')
        
        diff =  cv.CreateImage((image.width,image.height), image.depth, image.channels)
        #计算和原图形的差图像
        for i in range(image.height):
            for j in range(image.width): 
                    diff[i,j] = abs(image[i,j]-ifft_image[i,j])
        self.display(diff, 'diff')

if __name__ == '__main__':
    q= Q4('fig5.jpg','save')
    q()
   
    
    
